package o2o.web.actions.tip;

import com.jinyou.utils.common.*;
import o2o.cache.tip.TipInfoPaotuiMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.tip.TipInfoPaotui;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.tip.TipInfoPaotuiVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.web.actions.agent.CityAgentMan;
import o2o.web.actions.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//提示信息
@Controller
public class TipInfoPaotuiAction {

    //按类别获取提示信息 --- 用户端
    @RequestMapping(method = RequestMethod.POST, value = "/user/tip/paotui/info/list")
    @ResponseBody
    public String user_type_list(String city, Double lat, Double lng, Integer tipType) {
        Long agentId = null;
        if (ValidateUtil.isNotNull(city)) {
            if (city.endsWith("市")) {
                city = city.substring(0, city.lastIndexOf("市"));
            }
            if (ValidateUtil.isNotLatLng(lat, lng)) {
                return AjaxResult.errorResult("经纬度不能为空");
            }
            //根据所在城市及经纬度获取最新的商圈
            CityAgentVO cityAgent = CityAgentMan.getCityAgent(city, lat, lng);
            if (null == cityAgent) {
                return AjaxResult.errorResult("您所在的位置尚未开通，请重新选择");
            }
            agentId = cityAgent.getId();
        }

        List<TipInfoPaotuiVO> list = listOfAgentId(agentId, tipType);
        if (!ValidateUtil.isAbsList(list)) {
            //代理为空的时候  获取平台的
            list = listOfAgentId(-1l, tipType);
        }
        if (null == list) {
            return AjaxResult.successResult(0, null);
        }
        return AjaxResult.successResult(list.size(), list);
    }

    //按类别获取提示信息
    @RequestMapping(method = RequestMethod.POST, value = "/tip/paotui/info/list")
    @ResponseBody
    public String type_list(Long agentId, Integer tipType) {
        List<TipInfoPaotuiVO> listOfAgentId = listOfAgentId(agentId, tipType);
        if (ValidateUtil.isAbsList(listOfAgentId)) {
            return AjaxResult.successResult(listOfAgentId.size(), listOfAgentId);
        }

        return AjaxResult.successResult(0, null);
    }

    private List<TipInfoPaotuiVO> listOfAgentId(Long agentId, Integer tipType) {
        List<TipInfoPaotui> list = TipInfoPaotuiMemory.getInstance().listOfType(agentId, tipType);
        if (ValidateUtil.isAbsList(list)) {
            List<TipInfoPaotuiVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                TipInfoPaotuiVO vo = new TipInfoPaotuiVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                // 处理图片地址问题
                if (ValidateUtil.isNotNull(vo.getImageUrl()) && ValidateUtil.isNotNetUrl(vo.getImageUrl())) {
                    vo.setImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getImageUrl());
                }
                if (ValidateUtil.isNotNull(vo.getImageBUrl()) && ValidateUtil.isNotNetUrl(vo.getImageBUrl())) {
                    vo.setImageBUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getImageBUrl());
                }
                // end
                voList.add(vo);
            }
            return voList;
        }
        return null;
    }


    //----------------------------------------管理
    //新增
    @RequestMapping(method = RequestMethod.POST, value = "/admin/tip/paotui/info/add")
    @ResponseBody
    public String shop_label_add(String token, TipInfoPaotui info, FileUploadInfo fileUploadInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("信息不完整，请填写完整");
        }

        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("请输入名称");
        }

        if (null == info.getTipType()) {
            return AjaxResult.errorResult("类别不能为空");
        }

        // 添加图片

        if (fileUploadInfo != null && fileUploadInfo.getImage() != null) {
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.GOODS_IMAGE, fileUploadInfo.getImage());
            if (!ValidateUtil.isNull(filePath)) {
                info.setImageUrl(filePath);
            }
        }

        // 第二张图片
        if (fileUploadInfo != null && fileUploadInfo.getImage1() != null) {
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.GOODS_IMAGE, fileUploadInfo.getImage1());
            if (!ValidateUtil.isNull(filePath)) {
                info.setImageBUrl(filePath);
            }
        }

        long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        info.setDelFlag(0);
        info.setCreateUser(user.getUsername());

        //存入数据库
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.TIP_INFO_PAOTUI, info);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("新增失败，请稍后再试");
        }

        //存入缓存
        TipInfoPaotuiMemory.getInstance().add(time);

        return AjaxResult.successResult();
    }

    //修改
    @RequestMapping(method = RequestMethod.POST, value = "/admin/tip/paotui/info/modify")
    @ResponseBody
    public String shop_label_modify(String token, TipInfoPaotui info, FileUploadInfo fileUploadInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("信息不完整，请填写完整");
        }

        if (ValidateUtil.isNotID(info.getId())) {
            return AjaxResult.errorResult("请选择要修改的");
        }

        if (null == info.getTipType()) {
            return AjaxResult.errorResult("类别不能为空");
        }

        TipInfoPaotui tipInfo = TipInfoPaotuiMemory.getInstance().getById(info.getId());
        if (null == tipInfo) {
            return AjaxResult.errorResult("您修改的已不存在，请查证");
        }

        if (null == info.getName()) {
            info.setName(tipInfo.getName());
        }
        String imageUrl = "";
        if (fileUploadInfo != null && fileUploadInfo.getImage() != null) {
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.GOODS_IMAGE, fileUploadInfo.getImage());
            if (!ValidateUtil.isNull(filePath)) {
                imageUrl = ",imageUrl='" + filePath + "'";
            }
        }

        String imageBUrl = "";
        if (fileUploadInfo != null && fileUploadInfo.getImage1() != null) {
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.GOODS_IMAGE, fileUploadInfo.getImage1());
            if (!ValidateUtil.isNull(filePath)) {
                imageBUrl = ",imageBUrl='" + filePath + "'";
            }
        }


        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("请输入类别名称");
        }


        //修改商品类别
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.TIP_INFO_PAOTUI).append(" set ")
                .append(" name='").append(info.getName()).append("',note='").append(info.getNote())
                .append("',updateUser='").append(user.getUsername()).append("' ")
                .append(",price=").append(info.getPrice())
                .append(imageUrl).append(imageBUrl)
                .append(",descs='").append(info.getDescs()).append("',placeholder='").append(info.getPlaceholder()).append("'")
                .append(",note='").append(info.getNote()).append("',extra1='").append(info.getExtra1()).append("',extra2='").append(info.getExtra2()).append("',extra3='").append(info.getExtra3()).append("'")
                .append(" where id = ").append(info.getId()).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //修改缓存
        TipInfoPaotuiMemory.getInstance().modify(info.getId());

        return AjaxResult.successResult();
    }


    //删除
    @RequestMapping(method = RequestMethod.POST, value = "/admin/tip/paotui/info/delete")
    @ResponseBody
    public String shop_label_delete(String token, Long id) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择要删除的");
        }

        TipInfoPaotui tipInfo = TipInfoPaotuiMemory.getInstance().getById(id);
        if (null == tipInfo) {
            return AjaxResult.errorResult("您要删除的已不存在");
        }

        //删除商品类别
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.TIP_INFO_PAOTUI).append(" set delFlag = 1,updateUser='").append(user.getUsername())
                .append("' where id = ").append(id).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }

        //在缓存中删除
        TipInfoPaotuiMemory.getInstance().run();

        return AjaxResult.successResult();
    }

}
